#include "jugador.h"

CJugador::CJugador(CTerrain *t, int id){
    setId(id);
	mph = 100.0; //+25 boost
	backmph = -20.0;
	turnangle = 0.6;
	backturnangle = -0.4;
	acc  = 100.0;
	
	//PARA LA CREACIÓN DE LOS CHECKPOINTS
    chp = 0;
    map=new RoadMap(t, id);
    check= map->nextCheckp(true);
    nchecks=map->nCheckpoints();
}

//PARA LA CREACIÓN DE LOS CHECKPOINTS
void CJugador::printPosition(void){
    if (fabs(ex - position.x) < 4 && fabs(ez - position.z) < 4) return;

    printf("checkpoints[%d].x=%.0f;\t", chp, position.x);
    printf("checkpoints[%d].z=%.0f;\t", chp++, position.z);

    if (chp%2 == 0) printf("\n");
    ex = position.x;
    ez = position.z;
}

void CJugador::moveForward(void){
    
    int boost = 0;
    float distancia;
    distancia = map->distance(position, map->checkpPosition());

    if (distancia<300){ 
        boost = 25;
    }    
    SetState(MODEL_RUN);
	velocity = CVector(mph+boost, 0.0, mph+boost);
	acceleration += CVector(acc, 0.0, acc);

    if (position.x < MINPOS || position.x > MAXPOS || position.z < MINPOS || position.z > MAXPOS)
        stepBack(1);

}

void CJugador::moveBackwards(void){
    SetState(MODEL_RUN);
	velocity = CVector(backmph, 0.0, backmph);
    acceleration += CVector(acc, 0.0, acc);
    
    if (position.x < MINPOS || position.x > MAXPOS || position.z < MINPOS || position.z > MAXPOS)
        stepForward(1);
}

void CJugador::turnRight(void){
	direction += turnangle;
    SetState(MODEL_RIGHT);
}

void CJugador::backturnRight(void){
	direction += backturnangle;
    SetState(MODEL_RIGHT);
}

void CJugador::turnLeft(void){
	direction -= turnangle;
	SetState(MODEL_LEFT);
}
 
void CJugador::backturnLeft(void){
	direction -= backturnangle;
	SetState(MODEL_LEFT);
}

void CJugador::stop(void){
	velocity = CVector (0.0, 0.0, 0.0);
	acceleration = CVector (0.0, 0.0, 0.0);
    modelState = MODEL_IDLE;
}


void CJugador::OnCollision(CObject *collisionObject){


    if (typeid(*collisionObject) == typeid(CTerrain)){
		position.y = ((CTerrain*)collisionObject)->GetHeight(position.x, position.z) + size/2;
        
    }else if (collisionObject->tipo == t_CONTRARIO){
        if (velocity.x < 0) stepForward(1);
        else stepBack(1);
        
    }else if (collisionObject->tipo == t_MONTANA){
        if (velocity.x < 0) stepForward(1);
        else stepBack(1);
        
     }else if (collisionObject->tipo == t_CHECKPOINT){
	    if (position.x - check.x <12.0 && position.z - check.z <12){
            check=map->nextCheckp(true);
            map->checkpidx+=32;
            chp=map->checkpidx;      
            stop();
		}
     }

}